﻿using System;
using System.IO;
using System.ComponentModel.Composition;
using System.Web.Mvc;
using PAMD.Business.Models;
using PAMD.Controllers.Helper;
using PAMD.Database.Services;
using System.Web.Security;
using PAMD.Controllers.Extension;
using PAMD.Database;
using System.Collections.Generic;
using System.Linq;
using System.Web.Script.Serialization;
using PAMD.Database.Model;

namespace PAMD.Controllers.Account
{
    [Export]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    [Authorize]
    public class ListingController : Controller
    {
        [Import(typeof(ProfileService))]
        private ProfileService ProfileService { get; set; }

        [Import(typeof(CommonService))]
        private CommonService CommonService { get; set; }

        [Import(typeof(ListingService))]
        private ListingService ListingService { get; set; }

        public ActionResult Index()
        {
            ListingModel model = new ListingModel();
            if (model.Countries == null)
            {
                model.Countries = CommonService.GetCountryList().ToSelectListItems();
            }
            return View(model);
        }

        public ActionResult AddNew(ListingModel model)
        {
            if (model.Countries == null)
            {
                model.Countries = CommonService.GetCountryList().ToSelectListItems();
            }

            string username = ((FormsIdentity)User.Identity).Ticket.UserData;

            var userDetail = ProfileService.GetByUserName(username);
            model.Listing.ContactNumber = userDetail.Mobile;
            model.Listing.Daily = true;

            if (userDetail.AddressID == 0)
                model.Address = null;
            else
                model.Address = ProfileService.GetAddreess(userDetail.AddressID);

            return View(model);
        }

        public ActionResult AddNewSave(ListingModel model)
        {
            if (model.Countries == null)
            {
                model.Countries = CommonService.GetCountryList().ToSelectListItems();
            }

            if (IsValidate())
            {
                string username = ((FormsIdentity)User.Identity).Ticket.UserData;
                var userDetail = ProfileService.GetByUserName(username);

                List<ListingPrice> listingPrice = new List<ListingPrice>();
                //Save Listing Price
                if (model.PriceListFinal != null && model.PriceListFinal.Length > 5)
                {
                    JavaScriptSerializer ser = new JavaScriptSerializer();
                    ListingPrice[] prices = (ListingPrice[])ser.Deserialize(model.PriceListFinal, typeof(ListingPrice[]));
                    if (prices.Length > 0)
                        listingPrice.AddRange(prices);
                }

                //Save Uploaded Pictures
                List<string> pictures = new List<string>();
                if (model.FileList != null && model.FileList.Length > 3)
                {
                    string[] files = model.FileList.Split(',');

                    foreach (string file in files)
                    {
                        if (file.Length > 4)
                        {
                            string src = Server.MapPath("~/UploadToDelete/") + file;
                            string newName = userDetail.ID + "_" + Utils.RandomNumber(10, 10000) + ".jpg";
                            string dest = Server.MapPath("~/ListingPicture/") + newName;
                            try
                            {
                                System.IO.File.Copy(src, dest, true);
                                pictures.Add(newName);
                            }
                            catch
                            {
                            }
                        }
                    }
                }

                int saved = ListingService.AddNewListing(userDetail, model.Listing, listingPrice, model.Address, pictures);
                if (saved > 0)
                {
                    return View("ConfirmListing", model);
                }
            }

            ViewBag.Error = "Error occured while saving data";
            return View(model);
        }

        public ActionResult ListAll(ListAllModel model)
        {
            string username = ((FormsIdentity)User.Identity).Ticket.UserData;
            var userDetail = ProfileService.GetByUserName(username);
            model.Result = ListingService.GetAllListing(userDetail);

            if (model.Result.Count == 0)
            {
                return View("NoListing");
            }

            return View(model);
        }

        public ActionResult View(int id)
        {
            ListingResult listingResult = ListingService.GetListing(id);
            ListingModel model = new ListingModel();
            model.Address = listingResult.Address;
            model.Listing = listingResult.Listing;

            JavaScriptSerializer ser = new JavaScriptSerializer();
            string prices = ser.Serialize(listingResult.Price);
            model.PriceListFinal = prices;

            string photos = string.Empty;
            model.FileList = listingResult.Photo.Select(p => p.FileName).Aggregate(photos, (a, v) => string.Format("{0},{1}", a, v));

            return View(model);
        }

        public ActionResult Edit(int id)
        {
            ListingResult listingResult = ListingService.GetListing(id);
            ListingModel model = new ListingModel();
            model.Address = listingResult.Address;
            model.Listing = listingResult.Listing;

            JavaScriptSerializer ser = new JavaScriptSerializer();
            string prices = ser.Serialize(listingResult.Price);
            model.PriceListFinal = prices;

            string photos = string.Empty;
            model.FileList = listingResult.Photo.Select(p => p.FileName).Aggregate(photos, (a, v) => string.Format("{0},{1}", a, v));

            if (model.Countries == null)
            {
                model.Countries = CommonService.GetCountryList().ToSelectListItems();
            }
            return View(model);
        }

        public ActionResult EditSave(ListingModel model)
        {
            if (model.Countries == null)
            {
                model.Countries = CommonService.GetCountryList().ToSelectListItems();
            }

            if (IsValidate())
            {
                string username = ((FormsIdentity)User.Identity).Ticket.UserData;
                var userDetail = ProfileService.GetByUserName(username);

                List<ListingPrice> listingPrice = new List<ListingPrice>();
                //Save Listing Price
                if (model.PriceListFinal != null && model.PriceListFinal.Length > 5)
                {
                    JavaScriptSerializer ser = new JavaScriptSerializer();
                    ListingPrice[] prices = (ListingPrice[])ser.Deserialize(model.PriceListFinal, typeof(ListingPrice[]));
                    if (prices.Length > 0)
                        listingPrice.AddRange(prices);
                }

                //Save Uploaded Pictures
                List<string> pictures = new List<string>();
                if (model.FileList != null && model.FileList.Length > 3)
                {
                    string[] files = model.FileList.Split(',');

                    foreach (string file in files)
                    {
                        if (file.Length > 4)
                        {
                            string src = Server.MapPath("~/ListingPicture/") + file;
                            string newName = userDetail.ID + "_" + Utils.RandomNumber(10, 10000) + ".jpg";
                            string dest = Server.MapPath("~/ListingPicture/") + newName;
                            try
                            {
                                System.IO.File.Copy(src, dest, true);
                                pictures.Add(newName);
                            }
                            catch
                            {
                            }
                        }
                    }
                }

                int saved = ListingService.UpdateListing(userDetail, model.Listing, listingPrice, model.Address, pictures);
                if (saved > 0)
                {
                    ViewBag.Message = "You parking drive saved successfuly.";
                    return View("ConfirmListing", model);
                }
            }

            ViewBag.Error = "Error occured while saving data";
            return View(model);
        }

        private bool IsValidate()
        {
            //TODO: server validation pending.
            return true;
        }
    }
}